const { PrismaClient } = require('@prisma/client');

// 使用与API相同的Prisma配置
const prisma = new PrismaClient({
  log: ['query'],
});

async function testApiPrisma() {
  try {
    console.log('=== 使用API相同的Prisma配置测试 ===\n');
    
    // 模拟API中的完整流程
    console.log('1. 获取用户...');
    const user = { id: 1, username: 'admin', email: 'admin@example.com', role: 'admin' };
    console.log('获取到的用户:', JSON.stringify(user, null, 2));
    
    const userId = user.id || 1;
    console.log('使用的用户ID:', userId);
    
    // 模拟API请求数据
    const requestData = {
      name: '测试任务API',
      keywords: '["美食","旅行"]',
      maxCount: '10',
      isRecurring: false,
      interval: null
    };
    
    console.log('\n2. 验证关键词格式...');
    let keywordsArray;
    try {
      keywordsArray = JSON.parse(requestData.keywords);
      if (!Array.isArray(keywordsArray)) {
        throw new Error('关键词必须是数组格式');
      }
      console.log('关键词验证通过:', keywordsArray);
    } catch (error) {
      console.error('关键词格式错误:', error.message);
      return;
    }
    
    console.log('\n3. 创建任务...');
    const task = await prisma.extractionTask.create({
      data: {
        name: requestData.name,
        keywords: requestData.keywords,
        maxCount: parseInt(requestData.maxCount),
        isRecurring: Boolean(requestData.isRecurring),
        interval: requestData.isRecurring ? parseInt(requestData.interval || 24) : null,
        createdBy: userId,
        nextRunAt: requestData.isRecurring ? new Date() : null
      },
      include: {
        creator: {
          select: {
            username: true
          }
        }
      }
    });
    
    console.log('✅ 任务创建成功:', {
      id: task.id,
      name: task.name,
      createdBy: task.createdBy,
      creator: task.creator
    });
    
    // 清理测试数据
    await prisma.extractionTask.delete({
      where: { id: task.id }
    });
    console.log('测试任务已删除');
    
  } catch (error) {
    console.error('❌ 测试失败:', error);
    console.error('错误详情:', {
      code: error.code,
      meta: error.meta,
      message: error.message
    });
  } finally {
    await prisma.$disconnect();
  }
}

testApiPrisma();
